package com.xinghou.platform.file.chain.command.shop;

import java.io.File;

import org.apache.commons.chain.Command;
import org.apache.commons.chain.Context;
import org.apache.commons.io.FileUtils;

import com.xinghou.platform.file.model.ResourceContext;
import com.xinghou.platform.util.ImageTools;

public class SaveDiskCommand implements Command{

	@Override
	public boolean execute(Context context) throws Exception {
		@SuppressWarnings("unchecked")
		ResourceContext<byte[], String> resourceContext = (ResourceContext<byte[], String>)context;
		
		String absSourcePath = resourceContext.getSource().getRootPath() + resourceContext.getSource().getPath() 
				+ resourceContext.getSource().getSubPath();
		String absThumbnailsPath = resourceContext.getExtars()[0].getRootPath() + resourceContext.getExtars()[0].getPath() 
				+ resourceContext.getExtars()[0].getSubPath();
		
		//如果目录不存在 则创建
		File absSourceFolder = new File(absSourcePath);
		File absThumbnailsFolder = new File(absThumbnailsPath);
		
		if(!absSourceFolder.exists()){
			absSourceFolder.mkdirs();
		}
		if(!absThumbnailsFolder.exists()){
			absThumbnailsFolder.mkdirs();
		}
		
		byte[] data = (byte[])resourceContext.getRequest().getBody();
		//原始图片保存磁盘
		File source = new File(absSourcePath + File.separator + resourceContext.getSource().getResourceName());
		ImageTools.resize(data, source);
		//生成缩略图
		ImageTools.CreateThumbnail(data, absThumbnailsPath + File.separator + "160"+resourceContext.getSource().getResourceName(), "jpg", 160, 160);
		
		return false;
	}


}
